class LoadVirtualOptionsSolution {
    constructor(options = {}) {
        this.selectName = options.selectName || {};
        this.dataMap = new Map();
        this.searchTextMap = new Map();
        this.form = options.form;
        this.layer = options.layer;
        this.$ = options.$;
    }

    // Add setInputValue as a class method
    setInputValue(selectId, value) {
        const select = document.getElementById(selectId);
        const $select = this.$(select).next('.layui-form-select');
        const $input = $select.find('input');
        $input.val(value);
    }

    // 加载数据到指定的 select
    loadData(selectId, data) {
        this.dataMap.set(selectId, data);
        this.loadVirtualOptions(selectId, data);
    }

    // 批量加载数据
    loadBatchData(dataMap) {
        for (const [selectId, data] of Object.entries(dataMap)) {
            this.loadData(selectId, data);
        }
    }

    
    // 虚拟滚动加载选项
    loadVirtualOptions(selectId, data) {
        const select = document.getElementById(selectId);
        const itemHeight = 42;
        const visibleItems = 10;
        const bufferItems = 5;
        let startIndex = 0;
        const that = this;
        const select_name = this.selectName[select.id] ?? select.name;

        // 初始化 select 元素的所有选项
        const initializeSelectOptions = () => {
            const fragment = document.createDocumentFragment();
            const defaultOption = select.querySelector('option[value=""]');
            select.innerHTML = '';
            select.appendChild(defaultOption ?? new Option(`请选择${select_name}`, ''));

            data.forEach(item => {
                const option = document.createElement('option');
                option.value = item.value;
                option.text = item.text;
                fragment.appendChild(option);
            });
            if (data.length === 0) {
                var text=  this.searchTextMap.get(selectId);
                if (text) {
                    const option = document.createElement('option');
                    option.value = text;
                    option.text = text;
                    fragment.appendChild(option);

                }
                
            }

            select.appendChild(fragment);
        };

        // 更新可见选项
        const updateVisibleOptions = (scrollTop) => {
            const $select = this.$(select).next('.layui-form-select');
            const $dl = $select.find('dl.layui-anim');
            
            $dl.css({
                'max-height': '300px',
                'overflow-y': 'auto'
            });

            startIndex = Math.floor(scrollTop / itemHeight);
            const start = Math.max(0, startIndex);
            const end = Math.min(data.length, startIndex + visibleItems + bufferItems);

            $dl.empty();

            if (start > 0) {
                $dl.append(this.$('<div>').css({
                    height: start * itemHeight + 'px',
                    padding: 0,
                    margin: 0
                }));
            }
            
            $dl.append(this.$('<dd lay-value="">请选择' + select_name + '</dd>'));
            if (data.length === 0) {
                $dl.append(this.$(`<dd lay-value="${this.searchTextMap.get(selectId)}">${this.searchTextMap.get(selectId)}</dd>`));
            }

            for (let i = start; i < end; i++) {
                const $dd = this.$('<dd></dd>')
                    .attr('lay-value', data[i].value)
                    .text(data[i].text);

                if (data[i].value === select.value) {
                    $dd.addClass('layui-this');
                }

                $dl.append($dd);
            }

            if (end < data.length) {
                $dl.append(this.$('<div>').css({
                    height: (data.length - end) * itemHeight + 'px',
                    padding: 0,
                    margin: 0
                }));
            }

            const totalHeight = (data.length + 1) * itemHeight;
            $dl.height(totalHeight);
        };
       
        // 获取过滤后的数据
        const getFilterData = (searchText) => {
            if (!searchText) {
                return this.dataMap.get(selectId) || [];
            }
            const searchValue = searchText.toLowerCase();
            return (this.dataMap.get(selectId) || []).filter(item =>
                item.text.toLowerCase().includes(searchValue) ||
                String(item.value).toLowerCase().includes(searchValue)
            );
        };
        const setInputValue=(value)=>{
            const $select = this.$(select).next('.layui-form-select');
            const $input = $select.find('input');
            $input.val(value);
        };
        // 处理事件
        const eventhandle = () => {
            const $select = this.$(select).next('.layui-form-select');
            const $dl = $select.find('dl.layui-anim');

            // 添加 form.on filter 监听
            this.form.on('select', (data) => {
                const selectId = data.elem.id;
                if (data.value) {
                    const items = this.dataMap.get(selectId);                 
                    if (items) {
                        let selectedItem = null;
                        items.forEach(item => {
                            if (String(item.value) === String(data.value)) {
                                selectedItem = item;
                            }
                        });
                        if (selectedItem) {
                            this.searchTextMap.set(selectId, selectedItem.text);
                        } else {
                            this.setInputValue(selectId, data.value);
                        }
                    }
                }
            });

            $select.off('click').on('click', '.layui-select-title', () => {
                requestAnimationFrame(() => {
                    updateVisibleOptions(0);
                    const $dl = $select.find('dl.layui-anim');
                    const $input = $select.find('input');
                    $input.val(this.searchTextMap.get(selectId) || '');
                    $input.attr('placeholder', `请选择${select_name}`);

                    $dl.css({
                        'max-height': '300px',
                        'overflow-y': 'auto'
                    });
                });
            });

            const handleSearch = this.debounce((e) => {
                requestAnimationFrame(() => {
                    const searchValue = this.$(e.target).val().toLowerCase();
                    this.searchTextMap.set(selectId, searchValue);
                    this.loadVirtualOptions(selectId, getFilterData(searchValue));
                    // console.log('on input', this.searchTextMap);
                    const $select = this.$(select).next('.layui-form-select');
                    $select.find('.layui-select-title').trigger('click');
                    this.setInputValue(selectId, this.searchTextMap.get(selectId) || '');
                    const $input = $select.find('input');
                    $input.trigger('focus');
                });
            }, 500);

            $select.off('keyup').on('keyup', 'input', handleSearch);

            let ticking = false;
            $dl.off('scroll').on('scroll', () => {
                if (!ticking) {
                    requestAnimationFrame(() => {
                        updateVisibleOptions($dl.scrollTop());
                        ticking = false;
                    });
                    ticking = true;
                }
            });
        };
        initializeSelectOptions();
        this.form.render('select');
        setTimeout(() => {
            eventhandle();
            updateVisibleOptions(0);
        }, 0);
    }

    debounce(fn, delay) {
        let timer = null;
        return (...args) => {
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
                fn.apply(this, args);
            }, delay);
        };
    }
}